import React from 'react';
import { inject, observer } from 'mobx-react';
import { WeaTableNew, WeaLogView } from 'comsMobx';

let WeaTable = WeaTableNew.WeaTable;
import {
  WeaTop,
  WeaTab,
  WeaRightMenu,
  WeaErrorPage,
  WeaTools,
  WeaDialog,
  WeaCheckbox,
  WeaPopoverHrm,
  WeaLocaleProvider,
} from 'ecCom';
import { Button, Modal } from 'antd';
import CoworkConstant from '../util/CoworkConstant';
import * as CoworkUtil from '../util/CoworkUtil';
import { toJS } from 'mobx';

const confirm = Modal.confirm;

const WeaLogViewComp = WeaLogView.Component;

const getLabel = WeaLocaleProvider.getLabel;
const { viewer } = WeaTools;
/**
 * 内容审批
 */
@inject('coworkDiscussApprovalStore')
@observer
class DiscussApproval extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showLog: false,
      targetId: '',
      value: '1',
      approvaLoading: false,
      deleteLoading: false,
    };
  }

  componentDidMount() {
    this.props.coworkDiscussApprovalStore.doInit();
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.location.key !== nextProps.location.key) {
      this.props.coworkDiscussApprovalStore.doInit();
    }
  }

  componentWillUnmount() {
    // 组件卸载时一般清理一些状态
    const { coworkDiscussApprovalStore } = this.props;
    coworkDiscussApprovalStore.setShowSearchAd(false);
    coworkDiscussApprovalStore.setSelectedKey(0);
    coworkDiscussApprovalStore.clearFormFields();
  }

  render() {
    const { coworkDiscussApprovalStore } = this.props;
    const {
      comsWeaTableStore,
      loading,
      form,
      topTab,
      selectedKey,
      conditioninfo,
      showSearchAd,
      sessionkey,
      deleteDialogVisible,
      logStore,
      status,
    } = coworkDiscussApprovalStore;
    const { logType, logSmallType } = toJS(status);
    const buttons = [
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@9kdv4q@onok`}
        type="primary"
        onClick={this.executeDeleteOk}
      >
        {getLabel(83446, '确定')}
      </Button>,
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@irmgvg@cancel`}
        type="ghost"
        onClick={this.closeDeleteDialog}
      >
        {getLabel(201, '取消')}
      </Button>,
    ];
    const buttonsAd = [
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@esyin4@search`}
        type="primary"
        onClick={this.onTabSearch}
      >
        {getLabel(197, '搜索')}
      </Button>,
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@bfg8r4@reset`}
        type="ghost"
        onClick={this.onTabReset}
      >
        {getLabel(2022, '重置')}
      </Button>,
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@04yuuf@cancel`}
        type="ghost"
        onClick={this.onTabCancel}
      >
        {getLabel(201, '取消')}
      </Button>,
    ];

    return (
      <div className="wea-cowork-discussManage">
        <WeaPopoverHrm
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaPopoverHrm@itie3d`}
        />

        <WeaRightMenu
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaRightMenu@hufpys`}
          datas={this.getRightMenu()}
          onClick={this.onRightMenuClick}
        >
          <WeaTop
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaTop@u15jdk`}
            title={getLabel(32575, '内容审批')}
            loading={loading}
            icon={CoworkConstant.icon}
            iconBgcolor={CoworkConstant.iconBgColor}
            buttonSpace={10}
            showDropIcon={true}
            dropMenuDatas={this.getRightMenu()}
            onDropMenuClick={this.onRightMenuClick}
            buttons={this.getTopButtons()}
          >
            <WeaTab
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaTab@176s2f`}
              datas={topTab}
              keyParam="groupid"
              onChange={this.changeTab}
              selectedKey={selectedKey}
              searchType={['base', 'advanced']}
              searchsBaseValue={
                form.isFormInit &&
                form.getFormParams() &&
                form.getFormParams().remark
              }
              setShowSearchAd={this.setShowSearchAd}
              showSearchAd={showSearchAd}
              hideSearchAd={this.hideSearchAd}
              searchsAd={CoworkUtil.getSearchs(form, conditioninfo, () => {
                coworkDiscussApprovalStore.setShowSearchAd(false);
                coworkDiscussApprovalStore.doTableLoading();
              })}
              buttonsAd={buttonsAd}
              onSearch={coworkDiscussApprovalStore.doTableLoading}
              onSearchChange={this.onSearchChange}
            />
            <WeaTable
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaTable@9penbu`}
              comsWeaTableStore={comsWeaTableStore}
              loading={loading}
              sessionkey={sessionkey}
              needScroll={true}
              hasOrder={true}
              getColumns={this.getNewColumns}
              onOperatesClick={this.onOperatesClick}
            />
          </WeaTop>

          <WeaDialog
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaDialog@4nn2d2`}
            visible={deleteDialogVisible}
            buttons={buttons}
            title={getLabel(131329, '信息确认')}
            style={{ width: 375, height: 100 }}
            onCancel={this.closeDeleteDialog}
          >
            <div
              style={{
                position: 'relative',
                textAlign: 'center',
                paddingTop: '25px',
              }}
            >
              <p style={{ height: '30px' }}>
                {getLabel(4918, '确定要删除该帖子吗？', 'note')}
              </p>
              <p>
                <WeaCheckbox
                  ecId={`${
                    (this && this.props && this.props.ecId) || ''
                  }_WeaCheckbox@thwad1`}
                  fieldName="isDeleteAll"
                  value={true}
                  viewAttr={1}
                  onChange={this.onCheckboxChange}
                />
                <span className="ml5">
                  {getLabel(4828, '同时删除该帖子的所有评论', 'note')}
                </span>
              </p>
            </div>
          </WeaDialog>
        </WeaRightMenu>

        <WeaLogViewComp
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaLogViewComp@61j1vb`}
          visible={this.state.showLog}
          onCancel={this.onLogViewCancel}
          logStore={logStore}
          logType={logType}
          logSmallType={logSmallType}
          targetId={this.state.targetId}
        />
      </div>
    );
  }

  setShowSearchAd = (bool) => {
    this.props.coworkDiscussApprovalStore.setShowSearchAd(bool);
  };

  hideSearchAd = () =>
    this.props.coworkDiscussApprovalStore.setShowSearchAd(false);

  onSearchChange = (v) => {
    this.props.coworkDiscussApprovalStore.appendFormFields({ remark: v });
  };

  onCheckboxChange = (value) => {
    this.props.coworkDiscussApprovalStore.setIsDeleteAll(value);
  };
  onLogViewCancel = () => this.setState({ showLog: false });

  // 打开删除对话框
  openDeleteDialog = (discussIds) => {
    const { coworkDiscussApprovalStore } = this.props;
    coworkDiscussApprovalStore.showDeleteDialog(true, discussIds);
  };

  // 删除对话框，确定按钮事件
  executeDeleteOk = () => {
    const { coworkDiscussApprovalStore } = this.props;
    const { discussIds, isDeleteAll } = coworkDiscussApprovalStore.formValus;

    let reloadTable = this.executeSearch;
    let closeDeleteDialog = this.closeDeleteDialog;

    coworkDiscussApprovalStore.batchDiscussDel(
      {
        discussIds,
        isDeleteAll, // 是否同时删除所有评论
        logSmallType: '9', // 内容审批日志标志
      },
      () => {
        closeDeleteDialog();
        reloadTable();
      },
    );
  };

  // 关闭删除对话框的回调
  closeDeleteDialog = () => {
    const { coworkDiscussApprovalStore } = this.props;
    coworkDiscussApprovalStore.showDeleteDialog(false);
  };

  // 切换tab事件
  changeTab = (theKey) => {
    const { coworkDiscussApprovalStore } = this.props;

    coworkDiscussApprovalStore.setSelectedKey(theKey);
    coworkDiscussApprovalStore.clearFormFields();

    this.executeSearch();
  };

  // top中的按钮
  getTopButtons() {
    let _disabled = !this.getTableSelectedValues().length;
    const buttons = [];
    buttons.push(
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@aibsss@approval`}
        type="primary"
        disabled={_disabled}
        loading={this.state.approvaLoading}
        onClick={this.discussApproval}
      >
        {getLabel(124907, '批量审批')}
      </Button>,
    );
    buttons.push(
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@ptp74y@delete`}
        type="primary"
        disabled={_disabled}
        loading={this.state.deleteLoading}
        onClick={this.discussDelete}
      >
        {getLabel(32136, '批量删除')}
      </Button>,
    );
    return buttons;
  }

  // 右键菜单
  getRightMenu() {
    let _disabled = !this.getTableSelectedValues().length;

    let btns = [];
    btns.push({
      key: 'search',
      icon: <i className="icon-coms-search" />,
      content: getLabel(197, '搜索'),
    });

    btns.push({
      key: 'discussApproval',
      icon: <i className="icon-coms-Custom" />,
      content: getLabel(124907, '批量审批'),
      disabled: _disabled,
    });
    btns.push({
      key: 'discussDelete',
      icon: <i className="icon-coms-Custom" />,
      content: getLabel(32136, '批量删除'),
      disabled: _disabled,
    });
    btns.push({
      key: 'BTN_LOG',
      icon: <i className="icon-coms-Print-log" />,
      content: `${getLabel(83, '日志')}`,
      onClick: () => this.onRightMenuClick('BTN_LOG'),
    });
    btns.push({
      key: 'ShowCustomColumns',
      icon: <i className="icon-coms-Custom" />,
      content: getLabel(382660, '显示定制列'),
    });
    /*
    btns.push({ key: "collection", icon: <i className='icon-coms-Custom'/>, content: '收藏' });
    btns.push({ key: "help", icon: <i className='icon-coms-Custom'/>, content: '帮助' });
    */
    return btns;
  }

  // 右键菜单事件绑定
  onRightMenuClick = (key) => {
    const { coworkDiscussApprovalStore } = this.props;
    if (key == 'search') {
      this.executeSearch();
    } else if (key == 'discussApproval') {
      this.discussApproval();
    } else if (key == 'discussDelete') {
      this.discussDelete();
    } else if (key == 'BTN_LOG') {
      this.setState({ showLog: true });
    } else if (key == 'ShowCustomColumns') {
      const { sessionkey, comsWeaTableStore } = toJS(
        coworkDiscussApprovalStore,
      );
      comsWeaTableStore.setColSetVisible(sessionkey, true);
      comsWeaTableStore.tableColSet(sessionkey, true);
    }
  };

  // 执行搜索方法（也可用于刷新table）
  executeSearch = () => {
    const { coworkDiscussApprovalStore } = this.props;
    coworkDiscussApprovalStore.setShowSearchAd(false);
    coworkDiscussApprovalStore.doTableLoading();
  };

  discussApproval = () => {
    this.executeButtonMethod('discussApproval');
  };

  discussDelete = () => {
    this.executeButtonMethod('discussDelete');
  };

  executeButtonMethod(type, values) {
    let that = this;
    const { coworkDiscussApprovalStore } = this.props;
    if (!values) {
      values = this.getTableSelectedValues();
    }
    let reloadTable = this.executeSearch;

    switch (type) {
      case 'discussApproval': {
        confirm({
          title: getLabel(4075, '确定审批选定的信息吗？', 'note'),
          content: '',
          onOk() {
            that.setState({ approvaLoading: true });
            coworkDiscussApprovalStore.batchDiscussApprove(
              {
                discussIds: values,
              },
              () => {
                that.setState({ approvaLoading: false });
                reloadTable();
              },
            );
          },
          onCancel() {},
        });
        break;
      }
      case 'discussDelete': {
        // this.openDeleteDialog(values);
        confirm({
          content: (
            <div className="wea-list-confirm">
              <p>{getLabel(4912, '确认要删除这些讨论记录吗?', 'note')}</p>
              <div className="list-confirm-text">
                <WeaCheckbox
                  ecId={`${
                    (this && this.props && this.props.ecId) || ''
                  }_WeaCheckbox@pv1p5y`}
                  onChange={this.valueChange}
                  value={that.state.value}
                />
                {getLabel(4828, '同时删除该帖子的所有评论?', 'note')}
              </div>
            </div>
          ),
          onOk() {
            let { value } = that.state;
            that.setState({ deleteLoading: true });
            coworkDiscussApprovalStore.batchDiscussDel(
              {
                discussIds: values,
                isDeleteAll: parseInt(value), // 是否同时删除所有评论
                logSmallType: '9', // 内容审批日志标志
              },
              () => {
                that.setState({ deleteLoading: false });
                reloadTable();
              },
            );
          },
          onCancel() {},
        });
        break;
      }
    }
  }

  valueChange = (value) => {
    this.setState({
      value,
    });
  };

  // 获得table选中行的主键值数组。若没选中任何一条，返回空数组
  getTableSelectedValues() {
    const { coworkDiscussApprovalStore } = this.props;
    const { comsWeaTableStore } = coworkDiscussApprovalStore;
    let values = comsWeaTableStore.selectedRowKeysAllPages;
    return values;
  }

  onTabSearch = () => {
    const { coworkDiscussApprovalStore } = this.props;
    coworkDiscussApprovalStore.setShowSearchAd(false);
    coworkDiscussApprovalStore.doTableLoading();
  };
  onTabReset = () => {
    const { coworkDiscussApprovalStore } = this.props;
    coworkDiscussApprovalStore.clearFormFields();
  };
  onTabCancel = () => {
    const { coworkDiscussApprovalStore } = this.props;
    coworkDiscussApprovalStore.setShowSearchAd(false);
  };

  onRemarkClick = (e) => {
    if (e.target.nodeName === 'IMG') {
      let img = e.target;
      img.setAttribute('data-imgsrc', img.src);
      img.setAttribute('class', 'formImgPlay');
      viewer(e);
    }
  };

  // 自定义过滤渲染
  getNewColumns = (columns) => {
    let newColumns = '';
    newColumns = columns.map((column) => {
      let newColumn = column;
      newColumn.render = (text, record) => {
        // 前端元素转义
        let valueSpan =
          record[`${newColumn.dataIndex}span`] !== undefined
            ? record[`${newColumn.dataIndex}span`]
            : record[newColumn.dataIndex];
        let url = '';
        if (newColumn.dataIndex == 'coworkid') {
          url = CoworkUtil.getViewCoworkUrl(record.coworkid);
        }
        if (newColumn.dataIndex === 'remark') {
          return (
            <div
              className={'cowork-tablename-remark wea-url'}
              dangerouslySetInnerHTML={{ __html: valueSpan }}
              onClick={this.onRemarkClick}
            />
          );
        }
        return url == '' ? (
          <div
            className="wea-url"
            dangerouslySetInnerHTML={{ __html: valueSpan }}
          />
        ) : (
          <div
            className="wea-url-name"
            dangerouslySetInnerHTML={{ __html: valueSpan }}
            style={{ cursor: 'pointer' }}
            title={text}
            onClick={() => {
              window.open(url);
            }}
          />
        );
      };
      return newColumn;
    });
    return newColumns;
  };

  // 表格单元格转义
  onOperatesClick = (record, index, operate, flag) => {
    let discussId = record.id;
    if (flag == 0) {
      // 审批
      this.executeButtonMethod('discussApproval', discussId);
    } else if (flag == 1) {
      // 删除
      this.executeButtonMethod('discussDelete', discussId);
    } else if (flag == 2) {
      // 日志
      this.setState({ showLog: true });
    }
  };
}

export default WeaTools.tryCatch(
  React,
  props => (
    <WeaErrorPage
      ecId={`${
        (this && this.props && this.props.ecId) || ''
      }_WeaErrorPage@oxw5oa`}
      msg={
        props.error
          ? props.error
          : getLabel(186, '对不起，该页面异常，请联系管理员！', 'error')
      }
    />
  ),
  { error: '' },
)(DiscussApproval);
